<template>
  <div class="createPost-container">
    <el-form ref="postForm" :model="postForm" :rules="rules" class="form-container">
      <sticky :z-index="10" :class-name="'sub-navbar '+(postForm.status===0?'draft':'publish')">
        <el-button
          v-loading="loading"
          style="margin-left: 10px;"
          type="success"
          @click="submitForm(1)"
        >{{$t('article.publish')}}</el-button>
        <el-button v-loading="loading" type="warning" @click="submitForm(0)">{{$t('article.draft')}}</el-button>
      </sticky>

      <div class="createPost-main-container">
        <el-row>
          <el-col :span="24">
            <el-form-item
              style="margin-bottom: 40px;"
              label-width="70px"
              :label="$t('article.title')"
              prop="title"
            >
              <el-input
                v-model="postForm.title"
                :rows="1"
                type="textarea"
                class="article-textarea"
                autosize
              />
            </el-form-item>

            <div class="postInfo-container">
              <el-row>
                <el-col :span="12">
                  <el-form-item
                    label-width="70px"
                    :label="$t('article.author')"
                    class="postInfo-container-item"
                    prop="author"
                  >
                    <el-input
                      v-model="postForm.author"
                      :rows="1"
                      type="textarea"
                      class="article-textarea"
                      autosize
                    />
                  </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item
                    label-width="70px"
                    :label="$t('article.categoryName')"
                    class="postInfo-container-item"
                  >
                    <el-cascader
                      :props="props"
                      :options="options"
                      v-model="postForm.categoryId"
                      :show-all-levels="false"
                      @change="handleChange"
                      ref="category"
                    ></el-cascader>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-col>
        </el-row>

        <el-form-item
          style="margin-bottom: 40px;"
          label-width="70px"
          :label="$t('article.description')"
        >
          <el-input
            v-model="postForm.description"
            :rows="1"
            type="textarea"
            class="article-textarea"
            autosize
          />
        </el-form-item>

        <el-form-item prop="content" style="margin-bottom: 30px;">
          <Tinymce ref="editor" v-model="postForm.content" :height="400" />
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script>
import Tinymce from '@/components/Tinymce'
import Upload from '@/components/Upload/SingleImage3'
import Sticky from '@/components/Sticky' // 粘性header组件
import { validURL } from '@/utils/validate'
import { fetchArticle, createArticle, updateArticle } from '@/api/article'
import { fetchLazyList } from '@/api/category'
import { mapGetters } from 'vuex'

const defaultForm = {
  status: 0, //状态
  title: '', //文章题目
  content: '', //文章内容
  description: '', //文章摘要
  id: undefined, //主键
  userId: undefined, //用户编号
  categoryId: undefined, //栏目编号
  categoryName: undefined //栏目名称
}

export default {
  name: 'ArticleDetail',
  components: { Tinymce, Upload, Sticky },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    ...mapGetters(['account'])
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === '') {
        this.$message({
          message: rule.field + '为必传项',
          type: 'error'
        })
        callback(new Error(rule.field + '为必传项'))
      } else {
        callback()
      }
    }

    return {
      postForm: Object.assign({}, defaultForm),
      loading: false,
      rules: {
        title: [{ required: true, message: 'title is required', trigger: 'blur' }],
        author: [{ required: true, message: 'author is required', trigger: 'blur' }]
      },
      tempRoute: {},
      options: [],
      props: {
        // lazy: false,
        value: 'id',
        label: 'name',
        leaf: 'hasChildren'
        // lazyLoad(node, resolve) {
        //   const { level } = node
        //   let pid = '0'
        //   if (level != 0) {
        //     pid = node.data.id
        //   }

        //   fetchLazyList(pid)
        //     .then(response => {
        //       const { code, data } = response
        //       if (code === 1) {
        //         Array.from(data).map(item => {
        //           item.hasChildren = !item.hasChildren
        //         })
        //         // 通过调用resolve将子节点数据返回，通知组件数据加载完成
        //         resolve(data)
        //       } else {
        //         this.$notify({
        //           title: '失败',
        //           message: '加载栏目数据失败',
        //           type: 'error',
        //           duration: 2000
        //         })
        //       }
        //     })
        //     .catch(error => {
        //       this.$notify({
        //         title: '异常',
        //         message: '加载栏目数据异常',
        //         type: 'error',
        //         duration: 2000
        //       })
        //     })
        // }
      }
    }
  },
  created() {
    this.fetchLazyList()
    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id
      this.fetchData(id)
    }
    this.tempRoute = Object.assign({}, this.$route)
  },
  methods: {
    handleChange(value) {
      const checkedNodes = this.$refs['category'].getCheckedNodes()
      this.postForm.categoryName = checkedNodes[0].data.name
      this.postForm.categoryId = checkedNodes[0].data.id
    },
    fetchLazyList() {
      fetchLazyList('0')
        .then(response => {
          const { code, data } = response
          if (code === 1) {
            this.options = data
          } else {
            this.$notify({
              title: '失败',
              message: '加载栏目数据失败',
              type: 'error',
              duration: 2000
            })
          }
        })
        .catch(error => {
          this.$notify({
            title: '异常',
            message: '加载栏目数据异常',
            type: 'error',
            duration: 2000
          })
        })
    },
    fetchData(id) {
      fetchArticle(id)
        .then(response => {
          this.postForm = response.data
          // set tagsview title
          this.setTagsViewTitle()
          // set page title
          this.setPageTitle()
        })
        .catch(err => {})
    },
    setTagsViewTitle() {
      const title = $t('Edit Article')
      const route = Object.assign({}, this.tempRoute, { title: `${title}` })
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    setPageTitle() {
      const title = $t('Edit Article')
      document.title = `${title}`
    },
    submitForm(status) {
      this.postForm.status = status
      this.postForm.userId = this.account
      this.$refs.postForm.validate(valid => {
        if (valid) {
          this.loading = true
          let fetch = null
          if (this.isEdit) {
            fetch = updateArticle(this.postForm)
          } else {
            fetch = createArticle(this.postForm)
          }
          fetch
            .then(response => {
              this.loading = false
              const { code, data } = response
              if (code === 1) {
                this.$notify({
                  title: '成功',
                  message: '操作成功',
                  type: 'success',
                  duration: 2000
                })
              } else {
                this.loading = false
                this.$notify({
                  title: '失败',
                  message: '操作失败',
                  type: 'error',
                  duration: 2000
                })
              }
            })
            .catch(error => {
              this.loading = false
              this.$notify({
                title: '异常',
                message: '操作异常' + error,
                type: 'error',
                duration: 2000
              })
            })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '~@/styles/mixin.scss';

.createPost-container {
  position: relative;

  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea /deep/ {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}
</style>
